package com.hrm.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.List;

public class GeneratorUtils {
	public static String FirstChar2Upper(String s){
		return s.substring(0,1).toUpperCase()+s.substring(1,s.length());
	}
	public static String FirstChar2Lower(String s){
		return s.substring(0,1).toLowerCase()+s.substring(1,s.length());
	}

	public static String Column2Property(String colName){
		String[] tmps=colName.split("_");
		String result=tmps[0].toLowerCase();
		for(int i=1;i<tmps.length;i++){
			result+=tmps[i].substring(0,1).toUpperCase()+tmps[i].substring(1,tmps[i].length()).toLowerCase();
		}
		return result;
	}
	public static String TableName2FileName(String tableName){
		String[] tmps=tableName.split("_");
		String result=tmps[0].substring(0,1).toUpperCase()+tmps[0].substring(1,tmps[0].length()).toLowerCase();
		for(int i=1;i<tmps.length;i++){
			result+=tmps[i].substring(0,1).toUpperCase()+tmps[i].substring(1,tmps[i].length()).toLowerCase();
		}
		return result;
	}
	
	
	public static boolean createEntityFile(String packageName,MyTable myTable){
		FileWriter fw=null;
		try {
			URL url=GeneratorUtils.class.getClassLoader().getResource("");
			String path=url.getPath().substring(1,url.getPath().length()).replace("build/classes/", "")+"src/"+packageName.replace(".", "/")+"/";
			String fileName=myTable.getEntityFileName()+".java";
			File file = new File(path);
			if(!file.exists()){
				file.mkdir();
			}
			file=new File(path+fileName);
			fw = new FileWriter(file);
			StringBuffer sBuffer = new StringBuffer();
			sBuffer.append("package "+packageName+";\n\n");
			sBuffer.append("import "+Config.UTILPERPACKAGE+".MyObject;\n\n");
			sBuffer.append("import javax.xml.bind.annotation.XmlRootElement;\n\n");
			sBuffer.append("@XmlRootElement\n");
			sBuffer.append("public class "+ myTable.getEntityFileName()+" extends MyObject{\n\n");
			sBuffer.append("\tprivate static final long serialVersionUID = 1L;\n\n");
			for(MyColumn column :myTable.getList()){
				sBuffer.append("\tprivate "+column.getJavaType()+" "+column.getJavaProperty()+";\n\n");
				sBuffer.append(createGetMethod(column.getJavaType(), column.getJavaProperty()));
				sBuffer.append(createSetMethod(column.getJavaType(), column.getJavaProperty()));
			}
			sBuffer.append("}\n");
		fw.write(sBuffer.toString(),0,sBuffer.length());  
		fw.flush();
		return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static boolean createDAOFile(String packageName,MyTable myTable){
		FileWriter fw=null;
		try {
			URL url=GeneratorUtils.class.getClassLoader().getResource("");
			String path=url.getPath().substring(1,url.getPath().length()).replace("build/classes/", "")+"src/"+packageName.replace(".", "/")+"/";
			String fileName=myTable.getEntityFileName()+"Mapper.java";
			File file = new File(path);
			if(!file.exists()){
				file.mkdir();
			}
			file=new File(path+fileName);
			fw = new FileWriter(file);
			StringBuffer sBuffer = new StringBuffer();
			sBuffer.append("package "+packageName+";\n\n");
			sBuffer.append("import java.util.List;\n");
			sBuffer.append("import java.util.Map;\n");
			sBuffer.append("import "+Config.ENTITYPACKAGE+"."+myTable.getEntityFileName()+";\n\n");
			sBuffer.append("public interface "+ myTable.getEntityFileName()+"Mapper {\n\n");
			sBuffer.append("\tpublic int delete"+myTable.getEntityFileName()+"ById(long id);\n\n");
			sBuffer.append("\tpublic "+myTable.getEntityFileName()+" select"+myTable.getEntityFileName()+"ById(long id);\n\n");
			sBuffer.append("\tpublic List<"+myTable.getEntityFileName()+"> select"+myTable.getEntityFileName()+"ByMap(Map<String,Object> map);\n\n");
			sBuffer.append("\tpublic List<"+myTable.getEntityFileName()+"> select"+myTable.getEntityFileName()+"("+myTable.getEntityFileName()+" "+FirstChar2Lower(myTable.getEntityFileName())+");\n\n");
			sBuffer.append("\tpublic List<"+myTable.getEntityFileName()+"> selectAll"+myTable.getEntityFileName()+"();\n\n");
			sBuffer.append("\tpublic int insert"+myTable.getEntityFileName()+"("+myTable.getEntityFileName()+" "+FirstChar2Lower(myTable.getEntityFileName())+");\n\n");
			sBuffer.append("\tpublic int update"+myTable.getEntityFileName()+"("+myTable.getEntityFileName()+" "+FirstChar2Lower(myTable.getEntityFileName())+");\n\n");
			sBuffer.append("\tpublic int delete"+myTable.getEntityFileName()+"("+myTable.getEntityFileName()+" "+FirstChar2Lower(myTable.getEntityFileName())+");\n\n");
			sBuffer.append("\tpublic int update"+myTable.getEntityFileName()+"ByMap(Map<String,Object> map);\n\n");
			sBuffer.append("\tpublic int delete"+myTable.getEntityFileName()+"ByMap(Map<String,Object> map);\n");
			sBuffer.append("\tpublic int getAll"+myTable.getEntityFileName()+"Counts();\n");
			sBuffer.append("\tpublic int get"+myTable.getEntityFileName()+"Counts("+myTable.getEntityFileName()+" "+FirstChar2Lower(myTable.getEntityFileName())+");\n");
			sBuffer.append("\tpublic int get"+myTable.getEntityFileName()+"CountsByMap(Map<String,Object> map);\n");
			sBuffer.append("}\n");
			fw.write(sBuffer.toString(),0,sBuffer.length());  
			fw.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static boolean createMapperFile(String packageName,MyTable myTable){
		FileWriter fw=null;
		try {
			URL url=GeneratorUtils.class.getClassLoader().getResource("");
			String path=url.getPath().substring(1,url.getPath().length()).replace("build/classes/", "")+"src/"+packageName.replace(".", "/")+"/";
			String fileName=myTable.getEntityFileName()+"Mapper.xml";
			File file = new File(path);
			if(!file.exists()){
				file.mkdir();
			}
			file=new File(path+fileName);
			fw = new FileWriter(file);
			StringBuffer sBuffer = new StringBuffer();
			String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
			String doctype="<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >";
			String mapper="<mapper namespace=\""+Config.DAOPACKAGE+"."+myTable.getEntityFileName()+"Mapper\">";
			sBuffer.append(xml+"\n");
			sBuffer.append(doctype+"\n");
			sBuffer.append(mapper+"\n\n");
			sBuffer.append(createResultMapXML(myTable));
			sBuffer.append(createDynamicXML(myTable.getEntityFileName(),myTable.getList()));
			sBuffer.append(createSelectAllXML(myTable.getEntityFileName(), myTable.getTableName()));
			sBuffer.append(createSelectAllCountsXML(myTable.getEntityFileName(), myTable.getTableName()));
			sBuffer.append(createSelectEntityXML(myTable.getEntityFileName(), myTable.getTableName(),myTable.getList()));
			sBuffer.append(createSelectEntityCountsXML(myTable.getEntityFileName(), myTable.getTableName(),myTable.getList()));
			sBuffer.append(createSelectMapXML(myTable.getEntityFileName(), myTable.getTableName()));
			sBuffer.append(createSelectMapCountsXML(myTable.getEntityFileName(), myTable.getTableName()));
			sBuffer.append(createSelectIDXML(myTable.getEntityFileName(), myTable.getTableName()));
			
			sBuffer.append(createDeleteIDXML(myTable.getEntityFileName(),myTable.getTableName()));
			sBuffer.append(createDeleteEntityXML(myTable.getEntityFileName(), myTable.getTableName(), myTable.getList()));
			sBuffer.append(createDeleteMapXML(myTable.getEntityFileName(), myTable.getTableName()));
			
			sBuffer.append(createInsertEntityXML(myTable.getEntityFileName(),myTable.getTableName(),myTable.getList()));
			
			sBuffer.append(createUpdateEntityXML(myTable.getEntityFileName(), myTable.getTableName(), myTable.getList()));
			sBuffer.append(createUpdateMapXML(myTable.getEntityFileName(), myTable.getTableName(), myTable.getList()));
			
			sBuffer.append("</mapper>");
			
			fw.write(sBuffer.toString(),0,sBuffer.length());  
			fw.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static boolean createSqlMapConfigXML(List<String> entities){
		FileWriter fw=null;
		try {
			URL url=GeneratorUtils.class.getClassLoader().getResource("");
			String path=url.getPath().substring(1,url.getPath().length()).replace("build/classes/", "")+"src/";
			String fileName="sqlMapConfig.xml";
			File file = new File(path);
			if(!file.exists()){
				file.mkdir();
			}
			file=new File(path+fileName);
			fw = new FileWriter(file);
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		sBuffer.append("<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n");
		sBuffer.append("<configuration>\n\n");
		sBuffer.append("<typeAliases>\n");
		for(String s:entities){
			sBuffer.append("<typeAlias type=\""+Config.ENTITYPACKAGE+"."+s+"\" alias=\""+s+"\" />\n");
		}
		sBuffer.append("</typeAliases>\n\n");
		sBuffer.append("<mappers>\n");
		for(String s:entities){
			sBuffer.append("<mapper resource=\""+Config.MAPPERPACKAGE.replaceAll("\\.", "/")+"/"+s+"Mapper.xml\"/>\n");
		}
		sBuffer.append("</mappers>\n");
		sBuffer.append("</configuration>\n");
		fw.write(sBuffer.toString(),0,sBuffer.length());  
		fw.flush();
		return true;
	} catch (IOException e) {
		e.printStackTrace();
		return false;
	}finally{
		try {
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	}
	public static String createGetMethod(String type,String propertyName){
		return "\tpublic "+type+" get"+FirstChar2Upper(propertyName)+" (){"+"\n"+"\t\treturn this."+propertyName+";\n\t}\n\n";
	}
	public static String createSetMethod(String type,String propertyName){
		return "\tpublic void set"+FirstChar2Upper(propertyName)+" ("+type+" "+propertyName+"){"+"\n"+"\t\t this."+propertyName+"="+propertyName+";\n\t}\n\n";
	}
	
	public static String createSelectAllXML(String entityName,String tableName) {
		return "\t<select id=\"selectAll"+entityName+"\" resultMap=\""+entityName+"ResultMap\">\n"
					+"\t\tselect * from "+tableName+"\n"
						+"\t</select>\n\n";
	}
	public static String createSelectAllCountsXML(String entityName,String tableName) {
		return "\t<select id=\"getAll"+entityName+"Counts\" resultType=\"java.lang.Integer\">\n"
				+"\t\tselect count(0) from "+tableName+"\n"
				+"\t</select>\n\n";
	}
	public static String createDynamicXML(String entityName,List<MyColumn> columns) {
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t<sql id=\"dynamic"+entityName+"\">\n");
		sBuffer.append("\t\t<where>\n");
		sBuffer.append("\t\t\t1=1\n");
		for(MyColumn column:columns){
			sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			sBuffer.append("\t\t\t\tand "+column.getColname()+"=#{"+column.getJavaProperty()+"}\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		//根据ID删除数据时传多条ID
		sBuffer.append("\t\t\t<if test=\"ids != null\">\n");
		sBuffer.append("\t\t\t\tand id in \n");
		sBuffer.append("\t\t\t\t<foreach item=\"item\" index=\"index\" collection=\"ids\" \n");
		sBuffer.append("\t\t\t\t\topen=\"(\" separator=\",\" close=\")\">\n");
		sBuffer.append("\t\t\t\t\t\t#{item}\n");
		sBuffer.append("\t\t\t\t</foreach>\n");
		sBuffer.append("\t\t\t</if>\n");
	
		//分页条件判断
		sBuffer.append("\t\t\t<if test=\"currentStart != null\">\n");
		sBuffer.append("\t\t\t\tlimit #{currentStart},#{currentEnd}\n");
		sBuffer.append("\t\t\t</if>\n");
		
		sBuffer.append("\t\t</where>\n");
		sBuffer.append("\t</sql>\n\n");
		return sBuffer.toString();
	}
	public static String createSelectIDXML(String entityName,String tableName) {
		return "\t<select id=\"select"+entityName+"ById\" parameterType=\"java.lang.Long\" resultMap=\""+entityName+"ResultMap\">\n"
				+"\t\tselect * from "+tableName+" where id=#{id}\n"+
				"\t</select>\n\n";
	}
	public static String createDeleteIDXML(String entityName,String tableName) {
		return "\t<delete id=\"delete"+entityName+"ById\" parameterType=\"java.lang.Long\">\n"
				+"\t\tdelete from "+tableName+" where id=#{id}\n"+
				"\t</delete>\n\n";
	}
	public static String createSelectEntityXML(String entityName,String tableName,List<MyColumn> columns){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t\t<where>\n");
		sBuffer.append("\t\t\t1=1\n");
		for(MyColumn column:columns){
			if("int".equals(column.getJavaType())||"long".equals(column.getJavaType())||"double".equals(column.getJavaType())){
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != 0\">\n");
			}else{
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			}
			sBuffer.append("\t\t\t\tand "+column.getColname()+"=#{"+column.getJavaProperty()+"}\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</where>\n");
		return "\t<select id=\"select"+entityName+"\" parameterType=\""+entityName+"\" resultMap=\""+entityName+"ResultMap\">\n"
				+"\t\tselect * from "+tableName+"\n"+
				sBuffer.toString()+
				"\t</select>\n\n";
		
	}
	public static String createSelectEntityCountsXML(String entityName,String tableName,List<MyColumn> columns){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t\t<where>\n");
		sBuffer.append("\t\t\t1=1\n");
		for(MyColumn column:columns){
			if("int".equals(column.getJavaType())||"long".equals(column.getJavaType())||"double".equals(column.getJavaType())){
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != 0\">\n");
			}else{
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			}
			sBuffer.append("\t\t\t\tand "+column.getColname()+"=#{"+column.getJavaProperty()+"}\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</where>\n");
		return "\t<select id=\"get"+entityName+"Counts\" parameterType=\""+entityName+"\" resultType=\"java.lang.Integer\">\n"
				+"\t\tselect count(0) from "+tableName+"\n"+
				sBuffer.toString()+
				"\t</select>\n\n";
	}
	public static String createSelectMapXML(String entityName,String tableName){
		return "\t<select id=\"select"+entityName+"ByMap\" parameterType=\"map\" resultMap=\""+entityName+"ResultMap\">\n"
				+"\t\tselect * from "+tableName+"\n"+
				"\t\t<include refid=\"dynamic"+entityName+"\" />\n"+
				"\t</select>\n\n";
	}
	public static String createSelectMapCountsXML(String entityName,String tableName){
		return "\t<select id=\"get"+entityName+"CountsByMap\" parameterType=\"map\" resultType=\"java.lang.Integer\">\n"
				+"\t\tselect count(0) from "+tableName+"\n"+
				"\t\t<include refid=\"dynamic"+entityName+"\" />\n"+
				"\t</select>\n\n";
	}
	public static String createDeleteMapXML(String entityName,String tableName){
		return "\t<delete id=\"delete"+entityName+"ByMap\" parameterType=\"map\">\n"
				+"\t\tdelete from "+tableName+"\n"+
				"\t\t<include refid=\"dynamic"+entityName+"\" />\n"+
				"\t</delete>\n\n";
	}
	
	public static String createDeleteEntityXML(String entityName,String tableName,List<MyColumn> columns) {
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t<delete id=\"delete"+entityName+"\" parameterType=\""+entityName+"\">\n");
		sBuffer.append("\t\tdelete from "+tableName+"\n");
		sBuffer.append("\t\t<where>\n");
		sBuffer.append("\t\t\t1=1\n");
		for(MyColumn column:columns){
			if("int".equals(column.getJavaType())||"long".equals(column.getJavaType())){
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != 0\">\n");
			}else{
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			}
			sBuffer.append("\t\t\t\tand "+column.getColname()+"=#{"+column.getJavaProperty()+"}\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</where>\n");
		sBuffer.append("\t</delete>\n\n");
		return sBuffer.toString();
	}
	
	public static String createInsertEntityXML(String entityName,String tableName,List<MyColumn> columns){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t<insert id=\"insert"+entityName+"\" parameterType=\""+entityName+"\" useGeneratedKeys=\"true\" keyProperty=\"id\">\n");
		sBuffer.append("\t\tinsert into "+tableName+"\n");
		sBuffer.append("\t\t<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n");
		for(MyColumn column:columns){
			if("int".equals(column.getJavaType())||"long".equals(column.getJavaType())){
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != 0\">\n");
			}else{
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			}
			sBuffer.append("\t\t\t\t"+column.getColname()+",\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</trim>\n");
		sBuffer.append("\t\t<trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n");
		
		for(MyColumn column:columns){
			if("int".equals(column.getJavaType())||"long".equals(column.getJavaType())){
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != 0\">\n");
			}else{
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			}
			sBuffer.append("\t\t\t\t#{"+column.getJavaProperty()+"},\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</trim>\n");
		sBuffer.append("\t</insert>\n");
		return sBuffer.toString();
	}
	public static String createUpdateEntityXML(String entityName,String tableName,List<MyColumn> columns){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t<update id=\"update"+entityName+"\" parameterType=\""+entityName+"\">\n");
		sBuffer.append("\t\tupdate "+tableName+"\n");
		sBuffer.append("\t\t<set>\n");
		for(MyColumn column:columns){
			if("id".equals(column.getColname())){
				continue;
			}
			if("int".equals(column.getJavaType())||"long".equals(column.getJavaType())){
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != 0\">\n");
			}else{
				sBuffer.append("\t\t\t<if test=\""+column.getJavaProperty()+" != null\">\n");
			}
			sBuffer.append("\t\t\t\t"+column.getColname()+"=#{"+column.getJavaProperty()+"},\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</set>\n");
		sBuffer.append("\t\twhere id = #{id}\n");
		sBuffer.append("\t</update>\n");
		return sBuffer.toString();
	}
	public static String createUpdateMapXML(String entityName,String tableName,List<MyColumn> columns){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("\t<update id=\"update"+entityName+"ByMap\" parameterType=\"map\">\n");
		sBuffer.append("\t\tupdate "+tableName+"\n");
		sBuffer.append("\t\t<set>\n");
		for(MyColumn column:columns){
			if("id".equals(column.getColname())){
				continue;
			}
			sBuffer.append("\t\t\t<if test=\"new"+FirstChar2Upper(column.getJavaProperty())+" != null\">\n");
			sBuffer.append("\t\t\t\t"+column.getColname()+"=#{"+column.getJavaProperty()+"},\n");
			sBuffer.append("\t\t\t</if>\n");
		}
		sBuffer.append("\t\t</set>\n");
		sBuffer.append("\t\t<include refid=\"dynamic"+entityName+"\" />\n");
		sBuffer.append("\t</update>\n");
		return sBuffer.toString();
	}
	
	public static String createResultMapXML(MyTable myTable) {
		StringBuffer sBuffer=new StringBuffer();
		sBuffer.append("\t<resultMap id=\""+myTable.getEntityFileName()+"ResultMap\" type=\""+myTable.getEntityFileName()+"\">\n");
		for(MyColumn c:myTable.getList()){
			sBuffer.append( "\t\t<result property=\""+c.getJavaProperty()+"\" column=\""+c.getColname()+"\"/>\n");
		}
        sBuffer.append("\t</resultMap>\n\n");
		return sBuffer.toString();
	}
	
}
